
package ivan.cheng.activitys;

import ivan.cheng.Const;
import ivan.cheng.R;
import ivan.cheng.adapter.PackageListAdapters.PackageListAdapter;
import ivan.cheng.utils.LogUtil;
import ivan.cheng.views.MyListView;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class PermissionDetailActivity extends UIActivity {
    
    private PackageListAdapter adapter;
    private PackageManager mPackageManager;
    private BroadcastReceiver loadFinish = new LoadFinishReceiver();
    private ArrayList<String> packageNameLst;
    private ArrayList<PackageInfo> packageList = new ArrayList<PackageInfo>();
    private String permissionName;
    private MyListView listView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.list_detail);
        mTitle = (TextView)findViewById(R.id.custom_title_txt);
		mTitle.setText(R.string.app_name);
        listView = (MyListView) this.findViewById(R.id.listbody);
        mPackageManager = this.getApplicationContext().getPackageManager();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        packageNameLst = bundle.getStringArrayList(Const.EXTRA_PACKAGENAME_LIST);
        permissionName = bundle.getString(Const.EXTRA_PERMISSION_NAME);
        IntentFilter filter = new IntentFilter(Const.ACTION_DETAIL_LOADFINISH);
        this.registerReceiver(loadFinish, filter);
        
        //ComponentName cn = new ComponentName(pkg, cls)
       // mPackageManager.setComponentEnabledSetting(componentName, newState, flags)
        listView.setOnItemClickListener(new OnItemClickListener() 
        {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{//试试看能否禁止开机启动
				showInstalledAppDetails(packageNameLst.get(position - 1));
			}
		});
        //添加列表的头部信息，这个要放在setadapter之前
        View view = LayoutInflater.from(PermissionDetailActivity.this).inflate(R.layout.explain_head_item, null);
        TextView tv = (TextView)view.findViewById(R.id.tv_explain);
        tv.setText(Html.fromHtml(GetPermissionExplain(permissionName)));
        getListView().addHeaderView(view,null,false);
        //获取数据刷新列表
        refresh();
    }

    /**
     * 显示系统设置应用程序详细界面
     * 
     * @param packageName
     */
    public void showInstalledAppDetails(String packageName) {  
        Intent intent = new Intent();  
        final int apiLevel = Build.VERSION.SDK_INT;  
        if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口  
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");  
            Uri uri = Uri.fromParts("package", packageName, null);  
            intent.setData(uri);  
        } else { // 2.3以下，使用非公开的接口
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。  
            final String appPkgName = (apiLevel == 8 ? "pkg"  
                    : "com.android.settings.ApplicationPkgName");  
            intent.setAction(Intent.ACTION_VIEW);  
            intent.setClassName("com.android.settings",  
                    "com.android.settings.InstalledAppDetails");  
            intent.putExtra(appPkgName, packageName);  
        }  
        startActivity(intent);  
    }  
    
    private MyListView getListView() {
        return listView;
    }
    
    public void refresh() {
        setProgressBarIndeterminateVisibility(true);
        packageList.clear();
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() 
			{
				for(String name:packageNameLst)
				{
					try 
					{
						PackageInfo packageInfo = mPackageManager.getPackageInfo(name, PackageManager.GET_PERMISSIONS);
						packageList.add(packageInfo);
					} catch (NameNotFoundException e) {
						e.printStackTrace();
						LogUtil.w(e.toString()+ "   " + name);
					}
				}

				Intent in = new Intent(Const.ACTION_DETAIL_LOADFINISH);
				PermissionDetailActivity.this.sendBroadcast(in);
			}

		});
		t.start();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

	private String GetPermissionExplain(String sPermission) 
	{
		PermissionInfo tmpPermInfo = null;
		StringBuilder sb = new StringBuilder();
		try 
		{
			tmpPermInfo = mPackageManager.getPermissionInfo(sPermission, 0);// 通过permName得到该权限的详细信息
			PermissionGroupInfo pgi = mPackageManager.getPermissionGroupInfo(
					tmpPermInfo.group, 0);// 权限分为不同的群组，通过权限名，我们得到该权限属于什么类型的权限。
			sb.append("<b><font size=\"5\" color=\"0x3acbff\">权限类别</font></b>")
			.append("-" + pgi.loadLabel(mPackageManager).toString() + "<br>");
		} 
		catch (NameNotFoundException e) 
		{
			LogUtil.w("Could'nt retrieve permissions for package");
		}
		if(null != tmpPermInfo)
		{
			sb.append("<b><font size=\"5\" color=\"0x3acbff\">权限描述</font></b>")
			.append("-" + tmpPermInfo.loadLabel(mPackageManager).toString() + "<br>")
			.append("<b><font size=\"5\" color=\"0x3acbff\">权限详情</font></b>")
			.append("-" + tmpPermInfo.loadDescription(mPackageManager).toString()
					);
		}
		return sb.toString();
	}

    private class LoadFinishReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context ctx, Intent intent) {
            PermissionDetailActivity.this.setProgressBarIndeterminateVisibility(false);
            adapter = new PackageListAdapter(PermissionDetailActivity.this, packageList);
            
            PermissionDetailActivity.this.getListView().setAdapter(adapter);
        }
    }


	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(loadFinish);
	}

	@Override
	public void PackageAdded(String packageName) 
	{
		for(String name:packageNameLst)
		{
			if(name.equalsIgnoreCase(packageName))
			{
				packageNameLst.remove(name);
				refresh();
				break;
			}
		}
	}

	@Override
	public void PackageRemoved(String packageName) 
	{
		for(String name:packageNameLst)
		{
			if(name.equalsIgnoreCase(packageName))
			{
				packageNameLst.remove(name);
				refresh();
				break;
			}
		}
	}
    
}
